package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupDao dao;

    //设置检查项和检查组中间关系
    public void setCheckGroupAndCheckItem(Integer CheckGroupId, Integer[] CheckItemIds) {
        if (CheckItemIds.length > 0 && CheckItemIds != null) {
            for (Integer CheckItemId : CheckItemIds) {
                HashMap<String, Integer> map = new HashMap<>();
                map.put("CheckGroupId", CheckGroupId);
                map.put("CheckItemId", CheckItemId);
                dao.setCheckGroupAndCheckItem(map);
            }
        }
    }

    //添加
    @Override
    public void add(Integer[] checkitemIds, CheckGroup checkGroup) {
        dao.add(checkGroup);
        setCheckGroupAndCheckItem(checkGroup.getId(), checkitemIds);
    }


    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<CheckGroup> page = dao.queryByConditon(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    //删除
    @Override
    public void delete(Integer id) {
        int count = dao.findSetmealCountByCheckGroupId(id);
        if (count > 0) {
            //关联了检查套餐，不能删除
            throw new RuntimeException();
        } else {
            //没有关联
            dao.deleteCheckgroupAndCheckitem(id);//删除检查组和检查项关联数据
            dao.deleteCheckgroup(id);//删除检查组内容

        }
    }

    //根据ID查询检查组
    @Override
    public CheckGroup findById(Integer id) {
        return dao.findById(id);
    }

    //根据ID查询检查组关联的检查项
    @Override
    public List<Integer> findConnectionById(Integer id) {
        return dao.findConnectionById(id);
    }

    //编辑检查组
    @Override
    public void edit(Integer[] checkitemIds, CheckGroup checkGroup) {
        dao.edit(checkGroup); //修改检查组信息
        dao.deleteCheckgroupAndCheckitem(checkGroup.getId());//删除检查组和检查项的关系
        setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);
    }

    @Override
    public List<CheckGroup> findAll() {
        return dao.findAll();
    }
}
